import {
  readFileSync
} from 'fs';
import {
  transform
} from 'esbuild';



export default function SvgPlugin() {

  return {
    name: 'svg2jsx',
    enforce: "pre",
    async load(id) {

      if (id.endsWith('.svg')) {
        // 处理后缀svg的文件
        const {
          code,
          warnings
        } = await transform(
          // 在解析模块时调用，将源代码进行转换，输出转换后的结果，类似于 webpack 的 loader
          svgToJSX(readFileSync(id, "utf-8")), {
            loader: "jsx"
          }
        );
        for (const warning of warnings) {
          console.log(warning.location, warning.text);
        }
        return code; // 放回解析模块
      }
    }
  }
}


const svgToJSX = (svg) =>
  `import React from "react";
  const ReactComponent = (props) => (${svg
    .replace(/\s([a-z-:]*)="[^"]*"/gu, (string, key) => {
      if (key.startsWith('data-')) return string;
      const keyWithoutDashes = camelCaseOn(key, '-'); 
      let keyWithoutDots = camelCaseOn(keyWithoutDashes, ':');
      if (keyWithoutDots == 'class') keyWithoutDots = 'className';
      return string.replace(key, keyWithoutDots);
    })
    .replace('>', ' {...props}>')}); export default ReactComponent`;


const camelCaseOn = (str, delimiter) =>
  str
  .split(delimiter)
  .map((val, i) => (i === 0 ? val : val[0].toUpperCase() + val.slice(1))) // 首字母大写处理
  .join('');